package civicinity.ist.psu.edu.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import civicinity.ist.psu.edu.constants.Constants;

import android.util.Log;

public class DownloadHandler {

	
	public boolean downloadFiles(String fileURL, int eventID) {
		
		Log.i("K", "iCal download url : " + fileURL + " , eventID : " + eventID);
		
		int read;
		try {
			
			Log.i("K", "Start file downloads");
			
			URL urls = new URL(fileURL);
			
			Object getContent = urls.getContent();
			HttpURLConnection conn = (HttpURLConnection)urls.openConnection();
			conn.setReadTimeout(10 * 1000);
			conn.connect();
			
			int len = conn.getContentLength();
			
			byte[] buffer = new byte[1024];
			InputStream is = conn.getInputStream();
			FileOutputStream fos = new FileOutputStream(Constants.CIVICINITY_FILE_PATH + eventID + ".ics");
			
			Log.i("K", "HERE - 1");
			
			while((read = is.read(buffer)) > 0) {
				fos.write(buffer, 0, read);
			}
			
			Log.i("K", "HERE - 2");
			
			fos.close();
			is.close();
			
			return true;
			
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	
	//Download data
	public String downloadJson(String urlAddr){
		StringBuilder result = new StringBuilder();
		
		Log.i("K", "IN DOWNLOAD JSON : " + urlAddr);
		
		try{
			URL url = new URL(urlAddr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			if(conn != null){
				conn.setConnectTimeout(20 * 1000);
				conn.setUseCaches(false);
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream()));
					for(;;){
						String line = br.readLine();
						if (line == null) 
							break;
						result.append(line+'\n');
					}
					
					Log.i("K", "RESULT : " + result);
					
					br.close();
				}
				else{
					conn.disconnect();
					return null;
				}
				conn.disconnect();
			}
		}catch(Exception e){
			Log.e("K", e.toString());
			return null;
		}
		return result.toString();
	}
}
